'''
bot消息处理方式：主动update
'''
import configparser
import logging
import requests
import json

from telegram.ext import MessageHandler, Updater, CommandHandler, Filters
from musicCrawl import crawlSongs, crawlQQMusic

# Load data from config.ini file
config = configparser.ConfigParser()
config.read('config.ini')

# logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)
logger = logging.getLogger(__name__)

def start(bot, update):
    update.message.reply_text("Hi, this is a music search bot. input song's name to get it. like this：staring at you ")

def help(bot, update):
    update.message.reply_text("Input the song's name to get the music, like this：staring at you")

def neteasy_or_qqmusic(bot, update):
    update.message.reply_text("请输入歌名，例如：勇气（由于版权原因，有些歌可能搜不到哦~）")

def error(bot, update, error):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, error)

def getSongs(bot, update):
    song_url1 = crawlSongs(update.message.text)
    song_url2 = crawlQQMusic(update.message.text)
    if song_url1 == "songs not found..." and song_url2 == "songs not found...":
        update.message.reply_text(song_url1)
    else:
        if song_url1 == "songs not found...":
            song_url = song_url2
        elif song_url2 == "songs not found...":
            song_url = song_url1
        else:
            song_url = song_url2
            response = requests.post(url='https://api.telegram.org/bot{0}/{1}'.format((config['TELEGRAM']['TOKEN']), 'getFile'),
                                     data={'chat_id':update.message.chat_id, 'audio': song_url}).json()
        print(response)
        update.message.reply_text(song_url)
        bot.send_audio(chat_id=update.message.chat_id, audio=song_url, title=update.message.text)


def main():
    updater = Updater(token=(config['TELEGRAM']['TOKEN']), request_kwargs={'proxy_url':'socks5h://127.0.0.1:1080'})
    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help))
    dispatcher.add_handler(CommandHandler("neteasy", neteasy_or_qqmusic))
    dispatcher.add_handler(CommandHandler("qqmusic", neteasy_or_qqmusic))
    dispatcher.add_error_handler(error)

    dispatcher.add_handler(MessageHandler(Filters.text, getSongs))

    updater.start_polling(timeout=5)
    updater.idle()

if __name__ == '__main__':
    main()
